let qiniu = require('qiniu'),
    fs = require('fs'),
    path = require('path'),
    _config = require('./config/')

function getUptoken(accessKey, secretKey, bucket){
  let mac = new qiniu.auth.digest.Mac(accessKey, secretKey),
      options = {
        scope: bucket,
        returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
      },
      putPolicy = new qiniu.rs.PutPolicy(options)

  return putPolicy.uploadToken(mac);
}

// 华东	qiniu.zone.Zone_z0
// 华北	qiniu.zone.Zone_z1
// 华南	qiniu.zone.Zone_z2
function getUploader(index){
  if([0,1,2].indexOf(index) < 0){
    throw new Error('getUploader error: 请配置正确的储存区域')
  }
  let config = new qiniu.conf.Config()
  config.zone = qiniu.zone[`Zone_z${index}`]

  return new qiniu.form_up.FormUploader(config)
}

function uploadFile(uploadToken, key, localFile){
  let putExtra = new qiniu.form_up.PutExtra()

  formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
    respBody, respInfo) {
    if (respErr) {
      throw respErr;
    }

    if (respInfo.statusCode == 200) {
      console.log(`---文件名${respBody.key}---文件大小${respBody.fsize}---上传成功！`);
    } else {
      console.log(`---上传失败，状态码${respInfo.statusCode}`);
      console.log(respBody);
    }
  });
}

function getFileList(path){
  let fileList = []
  readFile(path, fileList)
  return fileList
}

function readFile(path, fileList){
  files = fs.readdirSync(path)
  files.forEach(item => {
    let state = fs.statSync(`${path}/${item}`)
    if(state.isDirectory()){
      readFile(`${path}/${item}`, fileList)
    } else {
      if(checkFile(`${path}/${item}`)){
        let obj = {
          size: state.size,//文件大小
          name: item,//文件名
          path: `${path}/${item}`//文件绝对路径
        }
        fileList.push(obj)
      }
    }
  })
}

function checkFile(path){
  for(let i = 0; i < uploadPath.length; i++){
    let pathPattern = new RegExp('^' + pathToReg(root) + uploadPath[i] + '$')
    let res = path.match(pathPattern)
    if(res !== null){
      return true
    }
  }
  return false
}

function pathToReg(str){
  // / => \/
  str = str.replace(/\//g, "\\/");
  // . => \.
  str = str.replace(/\./g, "\\.");
  // ** => .*
  str = str.replace(/\*\*/g, ".*");

  return str
}

function getKey(path){
  path = path.substring(root.length)
  return prefix + path
}

function write(filePath, prefix){
  let result = fs.readFileSync(filePath, { encoding: 'utf8' }).replace(/\/static/g, prefix)
  fs.writeFileSync(filePath, result)
}

let accessKey = _config.qiniu.ACCESS_KEY
let secretKey = _config.qiniu.SECRET_KEY
let bucket = _config.qiniu.BUCKET
let domain = _config.qiniu.DOMAIN
let root = _config.build.assetsRoot + '/' + _config.build.assetsSubDirectory
let uploadPath = _config.qiniu.uploadFiles
let prefix = _config.qiniu.prefix

let uploadToken = getUptoken(accessKey, secretKey, bucket)
let formUploader = getUploader(2)

let params = process.argv,
    version = params[2],
    versionResult = version.match(/^--version=(v\d+\.\d+\.\d+)$/)
if(versionResult !== null){
  version = versionResult[1]
  prefix += `/${version}`
} else {
  console.log('请输入版本号 node qiniu.js --version=v1.0.0');
}

let filesList = getFileList(root)
if(filesList.length <= 0){
  console.log('no file to upload');
} else {
  filesList.forEach(item => {
    let curPath = item.path
    let key = getKey(curPath)
    console.log(`-----file: ${curPath} is about to upload----`);
    uploadFile(uploadToken, key, curPath)
  })
}

let htmlFile = path.resolve(__dirname, _config.build.assetsRoot ,'index.html')

write(htmlFile, domain + prefix)//改成html文件中的引用路径为七牛地址
